﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using App1AppHandler;
using System.Net.Sockets;

namespace Reborn_WorldServer.App1AppHandler
{
    abstract public class PendingUserInput
    {
        private Timer expiresTimer;
        private Character _parentCharacter;
        public Character parentCharacter { get { return _parentCharacter; } }

        private long _id;
        public long id { get { return _id; } }

        public PendingUserInput(Character parentCharacter)
        {
            _parentCharacter = parentCharacter;
            _id = parentCharacter.addPendingInput(this);
        }

        private bool timerStarted = false;
        protected bool startExpireTimer(double interval)
        {
            if (timerStarted == true)
                return false;

            expiresTimer = new Timer(interval);
            expiresTimer.AutoReset = false;
            expiresTimer.Elapsed += new ElapsedEventHandler(expiresTimer_Elapsed);
            expiresTimer.Start();

            return true;
        }
        private void expiresTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            killTimeout();
            
            if (parentCharacter.removePendingInput(this) == true)
            {
                //Send close window data
                try
                {
                    parentCharacter.ClientSocket.socket.BeginSend("<cancelPendingInput id=\"" + id.ToString() + "\" />");
                }
                catch { }
            }
        }
        public void cancel()
        {
            expiresTimer_Elapsed(null, null);
        }

        private void killTimeout()
        {
            try
            {
                expiresTimer.Stop();
                expiresTimer.Dispose();
            }
            catch { }
        }

        protected void sendRequest(PendingUserInputData clientData)
        {
            try
            {
                parentCharacter.ClientSocket.socket.BeginSend(clientData.toXml(id));
            }
            catch { }
        }

        //Overriden in subclass
        virtual public bool processResult(string choice)
        {
            killTimeout();
            return parentCharacter.removePendingInput(this);
        }
        


    }
}
